package demo1.NiceDemo.picture;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class PictureView extends JPanel {
    private Image image;
    private Color backgroundColor;

    public void setBackgroundColor(Color backgroundColor) {
        this.backgroundColor = backgroundColor;
        this.repaint();
    }

    public void setImage(Image image) {
        this.image = image;
        this.repaint();
    }

    public void setImage(File file) {
        try {
            this.image = ImageIO.read(file);
            this.repaint();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void setImage(String resourcePath) {
        try {
            InputStream res = this.getClass().getResourceAsStream(resourcePath);
            this.image = ImageIO.read(res);
            this.repaint();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int width = this.getWidth();
        int height = this.getHeight();
        if (backgroundColor != null) {
            g.setColor(backgroundColor);
            g.fillRect(0, 0, width, height);
        }
        if(image != null) {
            //动态保持长宽比
            int imgW = image.getWidth(null);
            int imgH = image.getHeight(null);
            int fitW = width;
            int fitH = fitW * imgH / imgW;
            if (fitH > height) {
                fitH = height;
                fitW = fitH * imgW / imgH;
            }
            int fitX = (width - fitW) / 2;
            int fitY = (height - fitH) / 2;
            g.drawImage(image, fitX, fitY, fitW, fitH, null);
        }
    }
}
